from flask_sqlalchemy import SQLAlchemy
import pytz
from datetime import datetime
import uuid
import json

db = SQLAlchemy()

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    uuid = db.Column(db.String(36), unique=True, nullable=False, default=lambda: str(uuid.uuid4()))
    user_name = db.Column(db.String(80), nullable=False)
    public_key = db.Column(db.Text, nullable=False)
    private_key = db.Column(db.Text, nullable=False)
    is_active = db.Column(db.Boolean, default=True)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    # 修改历史记录 (JSON格式存储)
    history = db.Column(db.Text, default='[]')

    def get_id(self):
        return str(self.uuid)
    
    def add_history_entry(self, action, details):
        # 检查 history 是否为 None
        if self.history is None:
            self.history = '[]'
        try:
            history = json.loads(self.history)
        except json.JSONDecodeError:
            print("历史记录不是有效的 JSON 格式")
            history = []  # 如果解析失败，重置为一个空列表
        history.append({
            'timestamp': datetime.now(pytz.timezone('Asia/Shanghai')).isoformat(),  # 添加东八区时间戳
            'action': action,
            'details': details
        })
        self.history = json.dumps(history)

    def to_dict(self):
        return {
            'id': self.id,
            'uuid': self.uuid,
            'user_name': self.user_name,
            'public_key': self.public_key,
            'private_key': self.private_key,
            'is_active': self.is_active,
            'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S'),
            'history': self.history
        }